/**
 * Copyright 2013 Mr.Hai Mobile Developer. All rights reserved.
 * HAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hector.meinewerk.client.view.common;

import java.util.ArrayList;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hector.meinewerk.client.R;
import com.hector.meinewerk.client.view.widget.adapter.GalleryAdapter;
import com.hector.meinewerk.common.ActionEvent;
import com.hector.meinewerk.common.ActionEventConstant;
import com.hector.meinewerk.common.BaseActivity;
import com.hector.meinewerk.common.ModelEvent;
import com.hector.meinewerk.common.ServerPath;
import com.hector.meinewerk.controller.UserController;
import com.hector.meinewerk.model.Product;
import com.hector.meinewerk.utils.DateHelper;
import com.hector.meinewerk.utils.ImageLoader;
import com.hector.meinewerk.utils.StringUtil;

/**
 * 
 * screen product detail
 * 
 * @author: HaiTC3
 * @version: 1.1
 * @since: 1.0 | Mar 6, 2013
 */
public class ProductDetailActivity extends BaseActivity implements
		OnClickListener {
	// Variable
	private static final String TAG = "ProductDetailActivity";
	public static final String KEY_PRODUCT_ID = "productId";
	private String productId;
	private Product mProduct;
	private ImageLoader mImageLoader;

	// View
	private Button mBtnArrowLeft, mBtnArrowRight, mBtnBack;
	private ImageView mImageView;
	private Gallery mGallery;
	private GalleryAdapter mGallerryAdapter;

	// image view button back
	ImageView ivBack;
	// image view button home
	ImageView ivSetting;
	// image view button setting
	ImageView ivHome;

	// product info
	TextView tvName;
	TextView tvTag;
	TextView tvShortDesc;
	TextView tvPrice;
	TextView tvDiscount;
	TextView tvRemainProduct;
	TextView tvCurrency;
	TextView tvFeatureProduct;
	TextView tvSpecial;
	TextView tvActive;
	TextView tvCreateDate;
	TextView tvDescription;
	TextView tvOwnerEmail;
	TextView tvId;
	LinearLayout llEmail;
	ImageView ivLineEmail;
	ImageView ivEmail;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_detail);
		mProduct = Product.getCurrentProduct();
		mImageLoader = new ImageLoader(this);
		setupBundle();
		setupViews();
		updateUI();
		// requestGetProduct(productId);
	}

	private void setupBundle() {
		productId = getIntent().getStringExtra(KEY_PRODUCT_ID);
	}

	private void setupViews() {
		mBtnArrowLeft = (Button) findViewById(R.id.btn_arrow_left);
		mBtnArrowLeft.setOnClickListener(this);
		mBtnArrowRight = (Button) findViewById(R.id.btn_arrow_right);
		mBtnArrowRight.setOnClickListener(this);
		mImageView = (ImageView) findViewById(R.id.image_view);
		mGallery = (Gallery) findViewById(R.id.gallery);
		// mTxtTitle = (TextView) findViewById(R.id.txt_title);

		ivBack = (ImageView) this.findViewById(R.id.ivBack);
		ivBack.setOnClickListener(this);
		ivHome = (ImageView) this.findViewById(R.id.ivHome);
		ivHome.setOnClickListener(this);
		ivSetting = (ImageView) this.findViewById(R.id.ivSetting);
		ivSetting.setOnClickListener(this);

		mGallerryAdapter = new GalleryAdapter(mActivity);
		mGallery.setAdapter(mGallerryAdapter);
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				updateImage();
			}
		});
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				updateImage();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		tvName = (TextView) findViewById(R.id.tvName);
		tvTag = (TextView) findViewById(R.id.tvTag);
		tvShortDesc = (TextView) findViewById(R.id.tvShortDesc);
		tvPrice = (TextView) findViewById(R.id.tvPrice);
		tvDiscount = (TextView) findViewById(R.id.tvDiscount);
		tvRemainProduct = (TextView) findViewById(R.id.tvRemainProduct);
		tvCurrency = (TextView) findViewById(R.id.tvCurrency);
		tvFeatureProduct = (TextView) findViewById(R.id.tvFeatureProduct);
		tvSpecial = (TextView) findViewById(R.id.tvSpecial);
		tvActive = (TextView) findViewById(R.id.tvActive);
		tvCreateDate = (TextView) findViewById(R.id.tvCreateDate);
		tvDescription = (TextView) findViewById(R.id.tvDescription);
		tvOwnerEmail = (TextView) findViewById(R.id.tvOwnerEmail);
		tvId = (TextView) findViewById(R.id.tvId);
		ivLineEmail = (ImageView) findViewById(R.id.ivLineEmail);
		ivEmail = (ImageView) findViewById(R.id.ivEmail);
		ivEmail.setOnClickListener(this);
		llEmail = (LinearLayout) findViewById(R.id.llEmail);

	}

	/**
	 * 
	 * update UI
	 * 
	 * @param
	 * @return: void
	 * @author: HaiTC3
	 * @date: Mar 12, 2013
	 */
	private void updateUI() {
		if (!TextUtils.isEmpty(mProduct.getId()))
			tvId.setText(mProduct.getId());
		if (!TextUtils.isEmpty(mProduct.getName()))
			tvName.setText(mProduct.getName());
		if (!TextUtils.isEmpty(mProduct.getTags()))
			tvTag.setText(mProduct.getTags());
		if (!TextUtils.isEmpty(mProduct.getShortDesc()))
			tvShortDesc.setText(mProduct.getShortDesc());
		if (!TextUtils.isEmpty(String.valueOf(mProduct.getPrice())))
			tvPrice.setText(String.valueOf(mProduct.getPrice()));
		if (!TextUtils.isEmpty(String.valueOf(mProduct.getDiscount())))
			tvDiscount.setText(String.valueOf(mProduct.getDiscount()));
		if (!TextUtils.isEmpty(String.valueOf(mProduct.getRemainProduct())))
			tvRemainProduct
					.setText(String.valueOf(mProduct.getRemainProduct()));
		if (!TextUtils.isEmpty(String.valueOf(mProduct.getCurrency())))
			tvCurrency.setText(String.valueOf(mProduct.getCurrency()));
		if (mProduct.isFeatureProduct()) {
			tvFeatureProduct.setText("YES");
		} else {
			tvFeatureProduct.setText("NO");
		}
		if (mProduct.isSpeccial()) {
			tvFeatureProduct.setText("YES");
		} else {
			tvFeatureProduct.setText("NO");
		}
		if (mProduct.isActive()) {
			tvActive.setText("YES");
		} else {
			tvActive.setText("NO");
		}
		if (!TextUtils.isEmpty(mProduct.getCreateDate())) {
			try {
				tvCreateDate.setText(DateHelper.getDate(
						Long.parseLong(mProduct.getCreateDate()),
						DateHelper.RFC_USA_1));
			} catch (Exception e) {
				e.printStackTrace();
				tvCreateDate.setText("");
			}
		}
		if (!TextUtils.isEmpty(mProduct.getDescription())) {
			tvDescription.setText(Html.fromHtml(mProduct.getDescription()));
		}

		if (!StringUtil.isNullOrEmpty(mProduct.getOwnerEmail())) {
			tvOwnerEmail.setText(mProduct.getOwnerEmail());
			llEmail.setVisibility(View.VISIBLE);
			ivLineEmail.setVisibility(View.VISIBLE);
		} else {
			llEmail.setVisibility(View.GONE);
			ivLineEmail.setVisibility(View.GONE);
		}
		// mTxtTitle.setText(mProduct.getName());
		mGallerryAdapter.setArrayUrl(mProduct.getImage());
		mGallerryAdapter.notifyDataSetChanged();

		if (mGallerryAdapter.getCount() > 0) {
			mImageLoader.DisplayImage(mProduct.getImage()[0], mImageView);
		}
	}

	private void updateImage() {
		mImageLoader.DisplayImage((String) mGallerryAdapter.getItem(mGallery
				.getSelectedItemPosition()), mImageView);
	}

	@Override
	public void onClick(View v) {
		final int positionImage = mGallery.getSelectedItemPosition();
		switch (v.getId()) {
		case R.id.btn_arrow_left:
			if (positionImage >= mGallerryAdapter.getCount() - 1)
				return;
			mGallery.setSelection(positionImage + 1);
			updateImage();
			break;
		case R.id.btn_arrow_right:
			if (positionImage <= 0)
				return;
			mGallery.setSelection(positionImage - 1);
			updateImage();
			break;
		case R.id.ivEmail:
			gotoCreateOwenEmailAndSend();
			break;
		default:
			break;
		}
		if (v == ivBack) {
			this.finish();
		} else if (v == ivHome) {
			this.gotoMeineWerkAdmin();
		} else if (v == ivSetting) {

		}
	}

	/**
	 * 
	 * start activity send email
	 * 
	 * @author: HaiTC3
	 * @return: void
	 * @throws:
	 * @since: Mar 12, 2013
	 */
	public void gotoCreateOwenEmailAndSend() {
		String to = mProduct.getOwnerEmail();
		String subject = "SUBJECT EMAIL";
		String message = "MESSAGE";

		Intent email = new Intent(Intent.ACTION_SEND);
		email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
		email.putExtra(Intent.EXTRA_SUBJECT, subject);
		email.putExtra(Intent.EXTRA_TEXT, message);

		// need this to prompts email client only
		email.setType("message/rfc822");

		startActivity(Intent.createChooser(email, "Choose an Email client :"));
	}

	/**
	 * 
	 * display application meine werk admin
	 * 
	 * @author: HaiTC3
	 * @return: void
	 * @throws:
	 * @since: Mar 11, 2013
	 */
	public void gotoMeineWerkAdmin() {
		boolean checkExist = false;
		try {
			ApplicationInfo info = getPackageManager().getApplicationInfo(
					ServerPath.PACKAGE_APP_VER_ADMIN, 0);
			checkExist = true;
		} catch (PackageManager.NameNotFoundException e) {
			checkExist = false;
		}

		if (checkExist) {
			Intent i = new Intent();
			PackageManager manager = getPackageManager();
			i = manager
					.getLaunchIntentForPackage(ServerPath.PACKAGE_APP_VER_ADMIN);
			i.addCategory(Intent.CATEGORY_LAUNCHER);
			startActivity(i);
		} else {
			this.showDialog(StringUtil
					.getString(R.string.TEXT_NOTIFY_PACKAGE_NO_EXIST));
		}
	}

	private void requestGetProduct(String catergoryId) {
		// String catergoryId = String.valueOf(46);
		this.showProgressDialog(StringUtil.getString(R.string.LOADING));
		ArrayList<String> data = new ArrayList<String>();
		data.add(catergoryId);

		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.REQUEST_PRODUCT;
		event.userData = data;
		event.sender = this;

		UserController.getInstance().handleViewEvent(event);
	}

	/*
	 * xu ly cac su kien hoan thanh nhan tu controller
	 * 
	 * @see
	 * com.hector.meinewerk.common.BaseActivity#handleModelViewEvent(com.hector
	 * .meinewerk.common.ModelEvent)
	 */
	@Override
	public void handleModelViewEvent(ModelEvent modelEvent) {
		Log.v(TAG, "modelMessageSuccess: " + modelEvent.getModelMessage());
		ActionEvent event = modelEvent.getActionEvent();
		switch (event.action) {
		case ActionEventConstant.REQUEST_PRODUCT:
			final Product product = (Product) modelEvent.getModelData();
			mProduct = product;
			updateUI();
			this.closeProgressDialog();
			break;

		default:
			super.handleModelViewEvent(modelEvent);
			break;
		}
	}

	/*
	 * Xu ly cac su kien loi nhan tu controller
	 * 
	 * @see
	 * com.hector.meinewerk.common.BaseActivity#handleErrorModelViewEvent(com
	 * .hector.meinewerk.common.ModelEvent)
	 */
	@Override
	public void handleErrorModelViewEvent(ModelEvent modelEvent) {
		super.handleErrorModelViewEvent(modelEvent);
		Log.v(TAG, "modelMessageError: " + modelEvent.getModelMessage());
	}
}
